<template>
  <div class="scene-create-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">
          场景创建
        </h1>
      </div>
      <div class="header-actions">
        <el-button icon="Back" @click="goBack">返回</el-button>
        <el-button type="warning" icon="Brush" @click="clearCanvas">清空</el-button>
        <el-button type="success" icon="Check" @click="saveScene">保存</el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧设备列表 -->
      <div class="device-panel">
        <div class="panel-header">
          <h3>设备列表</h3>
        </div>
        
        <!-- 通用设备 -->
        <div class="device-group">
          <div class="group-title">通用设备</div>
          <div class="device-list">
            <div 
              v-for="device in generalDevices" 
              :key="device.type"
              class="device-item"
              draggable="true"
              @dragstart="handleDragStart($event, device)"
            >
              <el-icon :class="device.iconClass"><component :is="device.icon" /></el-icon>
              <span>{{ device.name }}</span>
            </div>
          </div>
        </div>

        <!-- 行业/协议设备 -->
        <div class="device-group">
          <div class="group-title">行业/协议设备</div>
          <div class="device-list">
            <div 
              v-for="device in industryDevices" 
              :key="device.type"
              class="device-item"
              draggable="true"
              @dragstart="handleDragStart($event, device)"
            >
              <el-icon :class="device.iconClass"><component :is="device.icon" /></el-icon>
              <span>{{ device.name }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧拓扑画布 -->
      <div class="canvas-panel">
        <!-- 画布工具栏 -->
        <div class="canvas-toolbar">
          <div class="toolbar-left">
            <el-icon><Share /></el-icon>
            <span>拓扑画布</span>
          </div>
          <div class="toolbar-center">
            <el-button 
              :type="currentTool === 'select' ? 'primary' : ''" 
              :icon="Pointer" 
              @click="setTool('select')"
              title="选择工具"
            />
            <el-button 
              :type="currentTool === 'pan' ? 'primary' : ''" 
              :icon="Position" 
              @click="setTool('pan')"
              title="平移工具"
            />
            <el-button 
              :icon="Connection" 
              @click="setTool('connect')"
              title="连接工具"
            />
            <el-button 
              :icon="Delete" 
              @click="deleteSelected"
              title="删除"
            />
            <el-button 
              :icon="RefreshLeft" 
              @click="undo"
              title="撤销"
            />
            <el-button 
              :icon="RefreshRight" 
              @click="redo"
              title="重做"
            />
          </div>
          <div class="toolbar-right">
            <el-button :icon="ZoomOut" @click="zoomOut" title="缩小" />
            <span class="zoom-level">{{ Math.round(zoom * 100) }}%</span>
            <el-button :icon="ZoomIn" @click="zoomIn" title="放大" />
            <el-button :icon="FullScreen" @click="fitToScreen" title="适应屏幕" />
            <el-button :icon="Grid" @click="toggleGrid" title="网格" />
            <el-button :icon="Setting" @click="alignNodes" title="对齐" />
            <el-button :icon="Brush" @click="clearCanvas" title="清空" />
          </div>
        </div>

        <!-- 画布容器 -->
        <div ref="canvasContainer" class="canvas-container"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Plus, 
  Back, 
  Delete, 
  Check, 
  Share, 
  Pointer, 
  Position, 
  Connection, 
  RefreshLeft, 
  RefreshRight, 
  ZoomOut, 
  ZoomIn, 
  FullScreen, 
  Grid, 
  Setting, 
  Brush,
  Monitor,
  Cpu,
  Lock,
  Platform,
  Camera,
  Switch,
  DataBoard,
  Lightning,
  Van,
  House,
  Location
} from '@element-plus/icons-vue'
import { Graph } from '@antv/x6'

const router = useRouter()

// 画布相关
const canvasContainer = ref(null)
let graph = null
const currentTool = ref('select')
const zoom = ref(1)

// 通用设备列表
const generalDevices = ref([
  { type: 'terminal', name: '终端', icon: 'Monitor', iconClass: 'terminal-icon' },
  { type: 'server', name: '服务器', icon: 'Cpu', iconClass: 'server-icon' },
  { type: 'router', name: '路由器', icon: 'Share', iconClass: 'router-icon' },
  { type: 'firewall', name: '防火墙', icon: 'Lock', iconClass: 'firewall-icon' },
  { type: 'cloud', name: '云平台', icon: 'Platform', iconClass: 'cloud-icon' },
  { type: 'camera', name: '摄像头', icon: 'Camera', iconClass: 'camera-icon' },
  { type: 'switch', name: '交换机', icon: 'Switch', iconClass: 'switch-icon' },
  { type: 'database', name: '数据库', icon: 'DataBoard', iconClass: 'database-icon' }
])

// 行业/协议设备列表
const industryDevices = ref([
  { type: 'modbus', name: 'Modbus设备', icon: 'Link', iconClass: 'modbus-icon' },
  { type: 'opcua', name: 'OPC UA设备', icon: 'Connection', iconClass: 'opcua-icon' },
  { type: 'dnp3', name: 'DNP3设备', icon: 'Lightning', iconClass: 'dnp3-icon' },
  { type: 'iec104', name: 'IEC104设备', icon: 'Share', iconClass: 'iec104-icon' },
  { type: 'drone', name: '无人机', icon: 'Van', iconClass: 'drone-icon' },
  { type: 'flightControl', name: '飞控系统', icon: 'Location', iconClass: 'flight-control-icon' },
  { type: 'power', name: '电力设备', icon: 'House', iconClass: 'power-icon' },
  { type: 'locomotive', name: '机车设备', icon: 'Van', iconClass: 'locomotive-icon' }
])

// 初始化画布
const initGraph = () => {
  if (!canvasContainer.value) return

  graph = new Graph({
    container: canvasContainer.value,
    grid: {
      visible: true,
      type: 'dot',
      size: 10,
      color: '#E2E2E2',
    },
    mousewheel: {
      enabled: true,
      modifiers: ['ctrl', 'meta'],
    },
    connecting: {
      anchor: 'center',
      connectionPoint: 'anchor',
      allowBlank: false,
      highlight: true,
      snap: true,
      createEdge() {
        return graph.createEdge({
          shape: 'edge',
          attrs: {
            line: {
              stroke: '#5F95FF',
              strokeWidth: 1,
              targetMarker: {
                name: 'block',
                width: 12,
                height: 8,
              },
            },
          },
          router: {
            name: 'manhattan',
          },
        })
      },
    },
    highlighting: {
      magnetAdsorbed: {
        name: 'stroke',
        args: {
          attrs: {
            fill: '#5F95FF',
            stroke: '#5F95FF',
          },
        },
      },
    },
    resizing: true,
    rotating: true,
    selecting: {
      enabled: true,
      multiple: true,
      rubberband: true,
      movable: true,
      showNodeSelectionBox: true,
    },
    keyboard: true,
    clipboard: true,
    history: true,
  })

  // 设置默认工具
  setTool('select')
}

// 设置工具
const setTool = (tool) => {
  currentTool.value = tool
  
  if (!graph) return

  switch (tool) {
    case 'select':
      graph.disablePanning()
      // 在select模式下允许拖拽创建节点
      break
    case 'pan':
      graph.enablePanning()
      break
    case 'connect':
      graph.disablePanning()
      break
  }
}

// 处理拖拽开始
const handleDragStart = (event, device) => {
  event.dataTransfer.setData('device', JSON.stringify(device))
}

// 缩放功能
const zoomIn = () => {
  if (graph) {
    const zoom = graph.zoom()
    if (zoom < 2) {
      graph.zoom(0.1)
      updateZoom()
    }
  }
}

const zoomOut = () => {
  if (graph) {
    const zoom = graph.zoom()
    if (zoom > 0.1) {
      graph.zoom(-0.1)
      updateZoom()
    }
  }
}

const updateZoom = () => {
  if (graph) {
    zoom.value = graph.zoom()
  }
}

// 适应屏幕
const fitToScreen = () => {
  if (graph) {
    graph.centerContent()
    graph.zoomToFit({ padding: 20 })
    updateZoom()
  }
}

// 切换网格
const toggleGrid = () => {
  if (graph) {
    const grid = graph.getGrid()
    graph.setGrid({
      ...grid,
      visible: !grid.visible,
    })
  }
}

// 对齐节点
const alignNodes = () => {
  if (graph) {
    const selectedNodes = graph.getSelectedCells().filter(cell => cell.isNode())
    if (selectedNodes.length > 1) {
      // 简单的垂直对齐
      const firstNode = selectedNodes[0]
      const y = firstNode.getPosition().y
      selectedNodes.slice(1).forEach(node => {
        const pos = node.getPosition()
        node.setPosition(pos.x, y)
      })
    }
  }
}

// 删除选中
const deleteSelected = () => {
  if (graph) {
    const selectedCells = graph.getSelectedCells()
    graph.removeCells(selectedCells)
  }
}

// 撤销
const undo = () => {
  if (graph) {
    graph.undo()
  }
}

// 重做
const redo = () => {
  if (graph) {
    graph.redo()
  }
}

// 清空画布
const clearCanvas = () => {
  if (graph) {
    graph.clearCells()
  }
}

// 保存场景
const saveScene = () => {
  if (graph) {
    const data = graph.toJSON()
    console.log('保存场景数据:', data)
    // 这里可以调用API保存数据
  }
}

// 返回
const goBack = () => {
  router.back()
}

onMounted(() => {
  console.log('场景创建页面已加载')
  initGraph()
  
  // 监听画布拖拽
  if (canvasContainer.value) {
    canvasContainer.value.addEventListener('dragover', (e) => {
      e.preventDefault()
    })
    
    canvasContainer.value.addEventListener('drop', (e) => {
      e.preventDefault()
      const deviceData = e.dataTransfer.getData('device')
      if (deviceData) {
        const device = JSON.parse(deviceData)
        const rect = canvasContainer.value.getBoundingClientRect()
        const x = e.clientX - rect.left
        const y = e.clientY - rect.top
        
        // 创建节点
        const node = graph.addNode({
          x: x,
          y: y,
          width: 80,
          height: 40,
          label: device.name,
          attrs: {
            body: {
              fill: '#fff',
              stroke: '#5F95FF',
              strokeWidth: 1,
            },
            label: {
              fill: '#333',
              fontSize: 12,
            },
          },
          ports: {
            groups: {
              in: {
                position: 'left',
                attrs: {
                  circle: {
                    r: 4,
                    magnet: true,
                    stroke: '#5F95FF',
                    strokeWidth: 1,
                    fill: '#fff',
                  },
                },
              },
              out: {
                position: 'right',
                attrs: {
                  circle: {
                    r: 4,
                    magnet: true,
                    stroke: '#5F95FF',
                    strokeWidth: 1,
                    fill: '#fff',
                  },
                },
              },
            },
          },
        })
        
        // 添加端口
        node.addPort({ group: 'in' })
        node.addPort({ group: 'out' })
      }
    })
  }
})

onUnmounted(() => {
  if (graph) {
    graph.dispose()
  }
})
</script>

<style lang="scss" scoped>
.scene-create-container {
  height: calc(100vh - 50px);
  display: flex;
  flex-direction: column;
}

  .header-left {
    .page-title {
      display: flex;
      align-items: center;
      gap: 10px;
      margin: 0;
      color: var(--text-color);
      font-size: 24px;
      font-weight: 600;
      
      .el-icon {
        font-size: 20px;
        color: var(--el-color-primary);
      }
    }
  }
  
  .header-actions {
    display: flex;
    gap: 12px;
  }


.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.device-panel {
  width: 280px;
  background: var(--card-bg);
  border-right: 1px solid var(--el-border-color-lighter);
  overflow-y: auto;
  
  .panel-header {
    padding: 16px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    
    h3 {
      margin: 0;
      color: var(--text-color);
      font-size: 16px;
      font-weight: 600;
    }
  }
  
  .device-group {
    padding: 16px;
    
    .group-title {
      font-weight: 600;
      color: var(--text-color);
      margin-bottom: 12px;
      font-size: 14px;
    }
    
    .device-list {
      display: flex;
      flex-direction: column;
      gap: 8px;
      
      .device-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 12px;
        background: var(--el-fill-color-lighter);
        border: 1px solid var(--el-border-color-lighter);
        border-radius: 6px;
        cursor: grab;
        transition: all 0.2s;
        
        &:hover {
          background: var(--el-fill-color);
          border-color: var(--el-color-primary);
        }
        
        &:active {
          cursor: grabbing;
        }
        
        .el-icon {
          font-size: 16px;
          
          &.terminal-icon { color: #f56c6c; }
          &.server-icon { color: #409eff; }
          &.router-icon { color: #409eff; }
          &.firewall-icon { color: #e6a23c; }
          &.cloud-icon { color: #909399; }
          &.camera-icon { color: #e6a23c; }
          &.switch-icon { color: #9c27b0; }
          &.database-icon { color: #67c23a; }
          &.modbus-icon { color: #9c27b0; }
          &.opcua-icon { color: #67c23a; }
          &.dnp3-icon { color: #f56c6c; }
          &.iec104-icon { color: #409eff; }
          &.drone-icon { color: #e6a23c; }
          &.flight-control-icon { color: #f56c6c; }
          &.power-icon { color: #67c23a; }
          &.locomotive-icon { color: #409eff; }
        }
        
        span {
          font-size: 14px;
          color: var(--text-color);
        }
      }
    }
  }
}

.canvas-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--card-bg);
  
  .canvas-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    background: var(--el-fill-color-lighter);
    
    .toolbar-left {
      display: flex;
      align-items: center;
      gap: 8px;
      font-weight: 600;
      color: var(--text-color);
      
      .el-icon {
        font-size: 16px;
        color: var(--el-color-primary);
      }
    }
    
    .toolbar-center {
      display: flex;
      gap: 4px;
      
      .el-button {
        width: 32px;
        height: 32px;
        padding: 0;
      }
    }
    
    .toolbar-right {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .el-button {
        width: 32px;
        height: 32px;
        padding: 0;
      }
      
      .zoom-level {
        font-size: 12px;
        color: var(--text-color-secondary);
        min-width: 40px;
        text-align: center;
      }
    }
  }
  
  .canvas-container {
    flex: 1;
    background: #fff;
    position: relative;
  }
}

// 响应式适配
@media (max-width: 1200px) {
  .device-panel {
    width: 240px;
  }
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }
  
  .device-panel {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid var(--el-border-color-lighter);
  }
  
  .canvas-panel {
    flex: 1;
  }
}
</style> 